<?php
/**
 * Created by : qicaitong.net
 * User: 内蒙古启讯科技信息有限公司
 * Tel: 15648133366（微信）
 */

namespace app\home\controller;

use app\common\model\Buylist;
use app\common\model\CourseOutline;
use app\common\model\CourseVideo;
use app\common\model\MenuLevel;
use Firebase\JWT\JWT;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use app\common\model\Curr;
use app\common\model\Product;
use app\common\model\CourseTeacher;

class Course extends Controller
{
    /**
     * 课程综合列表页面
     */
    public function lists()
    {
        $user_id = session::get('user')['user_id'];
        $input=input('');

        // 课程类目
        $menu_name = new Curr();
        // 课程难度
        $menu_level = new MenuLevel();

        // 从地址栏接收类目id
        if(isset($input['name'])){ $currid=$input['name']; } else { $currid=0;}
        if(isset($input['level'])){ $classes=$input['level']; } else { $classes=0;}

        // 实例化课程类
        $products = new Product();
        if($classes==0 && $currid==0){
            // 取出所有课程
            $products = $products->where('shopsxj', '=', '1')->order('sort asc')->paginate('50');
        }else{
            // 按照课程id和课程难度取出所有课程
            $where = array();
            if($classes == 0 && $currid != 0) {
                $where['currid']=$currid;
            }

            if($classes != 0 && $currid == 0) {
                $where['classes']=$classes;
            }

            if($classes != 0 && $currid != 0) {
                $where['currid']=$currid;
                $where['classes']=$classes;
            }

            $products = $products->where('shopsxj', '=', '1')->where($where)->order('sort asc')->paginate('50');
        }

        $area = Session::get('area');
        $this->assign('area', $area);

        // 传入课程类目及切换参数
        $this->assign('menu_name', $menu_name->get_menu_name());
        $this->assign('name', $currid);
        $this->assign('level', $classes);

        // 传入课程难度
        $this->assign('menu_level', $menu_level->get_menu_level());

        // 传入课程
        $this->assign('products', $products);
        return view('index/course_list');
    }

    /**
     * 课程详细介绍页面，包括课程介绍、章节、讲师等信息（非播放页面）
     */
    public function course_details() {
        // 获取课程编号
        $course_id = input('id/d');
        // 实例化课程模型
        $product = new Product();
        // 获取课程章节
        $category = $this->category($course_id);
        // 获取当前课程的老师
        $teacher = new CourseTeacher();
        $all_teacher = $teacher->get_teacher_by_courseid($course_id);
        // 数据传入
        $this->assign('course_id', $course_id); // 单个课程编号
        $this->assign('course', $product->getCourseId($course_id)); // 单个课程信息
        $this->assign('category', $category); // 课程章节
        $this->assign('teachers', $all_teacher); // 课程对应的老师们
        // 模板调用
        return view('index/course_details');
    }

    /**
     * 播放页面
     */
    public function play() {
        // 课程编号
        $id = input('id');
        // 章节视频编号
        $vid = input('vid');

        if($id == null || $id == '') {
            $this->error('缺少参数', url('/users/login'), '',1);
        }

        //是否登录
        $user = session('user');
        if(!Session::get('user')['user_id']){
            $this->error('您尚未登录系统', url('/users/login'), '', 1);
        }

        //校验课程是否存在
        $product = new Product();
        $product = $product->where('shopsxj', '=', '1')->find($id);
        if (!$product) {
            $this->error('课程暂未上架后参数错误，请联系客服老师!');
        }

        //购买状态校验
        $buy = new Buylist();
        $buy = $buy->where('uid', '=', Session::get('user')['user_id'])->where('product_id', '=', $id)->find();
        if ($buy) {
            // 购买记录存在
            $buyArray = $buy->toArray();
            // 购买过期期限在当前日期前，说明已购课程过期了。
            if ($buyArray['expTime'] && $buyArray['expTime'] < time()) {
                $buy->time = 0;
                $buy->expTime = null;
                $buy->buytime = time();
                $buy->save();
                $status = false;
            } else {
                // 购买的课程还没有过期则查询课程
                if ($buyArray['expTime'] && $buyArray['expTime'] > time()) {
                    $status = true;
                    $category = $this->category($id); // 综合获取,videoId,menu_id,cLogId,pid,grade,outline,title,tLen,watch_time,play_persent,time
                } else {
                    $status = false;
                }
            }
        } else {
            // 没有购买（此块逻辑可以删除，待测试）
            /*$buyNew = new Buylist();
            $buyNew->save(['product_id' => $id, 'uid' => Session::get('user')['user_id'], 'time' => '1',]);*/
            $status = false;
        }
        if (!$status) {
            $this->error('请先购买该课程');
        }

        // 读取课程章节
        if (!$vid) {
            for ($i = 0; $i < count($category['catalogs']); $i++) {
                if ($category['catalogs'][$i]['videoId']) {
                    $vid = $category['catalogs'][$i]['cLogId'];
                    break;
                }
            }
            $last_watch_video = Db::table('bk_video_time')
                ->where('menu_id', 'in', $category['watch_ids'])
                ->where('user_id', Session::get('user')['user_id'])
                ->order('watch_time desc')
                ->find();
            if ($last_watch_video['watch_time'] > 0) {
                $vid = $last_watch_video['menu_id'];
            }
        }

        $video_id = $vid;
        $video_type = 'normal';
        $video = new CourseVideo();

        $video = $video->where('menu_id',$vid)->find(); //逻辑错误

        if (!$video) {
            $this->error('课程视频不存在或者ID错误');
        }

        $this->assign('id', $id);
        $this->assign('video', $video->toArray());
        $this->assign('vid', input('get.video_id')); //课程章节主键
        $this->assign('video_id', $video_id);
        $this->assign('category', $category);
        $this->assign('thumb', $product['thumb']);
        $this->assign('sign', $this->getsign());
        return view('index/play');
    }

    public function category($id)
    {
        // 从product表关联的course_list表中取出某课程的章节，如java课程的第一章、第一节、第二节
        $one = 0;
        $two = 0;
        $lists = new \app\admin\model\Product();
        $lists = $lists->find($id);
        if (!$lists) {
            $this->error('该课程不存在！');
        }
        if ($lists instanceof \app\admin\model\Product) {
            $listsArray = $lists->getCourseList();
        } else {
            $this->error('getCourseList方法执行错误!');
        }
        // 从course_video表中取出章节的具体视频等信息、如第一节的视频地址等
        $video_obj = new CourseVideo();
        $cataLogs = array();
        $watch_ids = '';
        foreach ($listsArray as $key => $list) {
            $videoId = $video_obj->where(array('menu_id'=>$list['id']))->find();
            $item['videoId'] = $videoId['video_path'];
            $item['menu_id'] = $videoId['menu_id'];
            $watch_ids .= $list['id'] . ',';
            if ($list['parent_id'] > 0) {
                $one = $one + 1;
            }
            $item['cLogId'] = $list['id'];
            $item['pid'] = $list['parent_id'];
            $list['parent_id'] ? $item['grade'] = 1 : $item['grade'] = 0;
            if ($item['grade'] == '0') {
                $outline = new CourseOutline();
                $outline = $outline->where('menu_id', $list['id'])->find();

                $item['outline'] = $outline ? $outline->outline : '暂无大纲';
            }
            $item['title'] = $list['title'];
            $item['content'] = $list['content'];
            $item['tLen'] = $list['time'] ? $list['time'] : '暂无时长信息';
            $item['watch_time'] = 0;
            $play_persent = 0;
            if (strpos($list['time'], ':') !== false) {
                $timesss = explode(':', $item['tLen']);
                $timeone = $timesss[0] * 3600;
                $timeotwo = $timesss[1] * 60;
                $time = $timeone + $timeotwo + $timesss[2] - 10;
                $uid = Session::get('user')['user_id'];
                $butime = db('video_time')->where('menu_id', $list['id'])->where('user_id', $uid)->find();
                if ($butime) {
                    if ($butime['sec'] >= $time) {
                        $numtime = '已学100%';
                        if ($list['parent_id'] > 0) {
                            $two = $two + 1;
                        }
                        $play_persent = $butime['sec'];
                    } else if ($butime['sec'] < $time) {
                        $nuim = $butime['sec'] / $time * 100;
                        $timdf = intval($nuim);
                        $numtime = '已学' . $timdf . '%';
                        $play_persent = $timdf;
                    }
                } else {
                    $numtime = '未开始';
                }
            } elseif ($item['tLen'] == '暂无时长信息') {
                $numtime = '未开始';
            } else {
                $numtime = $item['tLen'];
            }
            $item['play_persent'] = $play_persent;
            $item['time'] = $numtime;
            $cataLogs[] = $item;

        }

        $watch_ids = rtrim($watch_ids, ',');
        $studyPro['sTime'] = $one;
        $studyPro['pro'] = $two;
        $result['code'] = '1';
        $result['studyPro'] = $studyPro;
        $result['watch_ids'] = $watch_ids;
        $result['catalogs'] = $cataLogs;
        return $result;
    }

    /**
     * 签名,该方法需要被移除，在首页起到默认加载视频的功能。
     */
    public function getsign() {
        $appId = 1500008102; // 用户 appid
        $fileId = "387702291721398311"; // 目标 FileId 387702292122781625 有些视频转码有问题
        $currentTime = time();
        $psignExpire = $currentTime + 3600; // 可任意设置过期时间，示例1h
        $urlTimeExpire = dechex($psignExpire); // 可任意设置过期时间，16进制字符串形式，示例1h
        $key = "gnvyy1OmzOtfNVLd2HD8";

        $payload = array(
            "appId" => $appId,
            "fileId" => $fileId,
            "currentTimeStamp" => $currentTime,
            "expireTimeStamp" => $psignExpire,
            "urlAccessInfo" => array(
                "t" => $urlTimeExpire
            )
        );

        $jwt = JWT::encode($payload, $key, 'HS256');
        return $jwt;
    }
}